﻿namespace DocumentMaking.Lib.ToolServices;

/// <summary>
/// 处理关键字替换的服务
/// </summary>
public static class KeywordReplaceService
{
    /// <summary>
    /// Replace all old key with the new key in a directory
    /// 用目录中的新密钥替换所有旧密钥
    /// </summary>
    /// <param name="directoryName">Directory Name</param>
    /// <param name="oldKey">The old keyword to be replaced</param>
    /// <param name="newKey">The new keyword</param>
    /// <exception cref="NotImplementedException"></exception>
    public static void ReplaceKeyword(string directoryName, string oldKey, string newKey)
    {
        // 如果文件夹既没有子文件夹也没有文件，如果需要直接重命名文件夹；
        // 否则如果文件夹有子文件夹，替换关键字递归；
        // 否则，如果文件夹中有文件，则根据需要重命名文件名，并根据需要替换其内容中的关键字。

        if (string.IsNullOrEmpty(directoryName) || string.IsNullOrEmpty(oldKey) || newKey == null)
            throw new ArgumentNullException($"{nameof(Directory)} or {nameof(oldKey)} couldn't be empty");

        if (Directory.Exists(directoryName))
            ReplaceKeywordRecursive(new DirectoryInfo(directoryName), oldKey, newKey);
        else
            throw new IOException("Directory Not Exists");
    }

    /// <summary>
    /// 用递归把目录中的新密钥替换所有旧密钥
    /// </summary>
    /// <param name="directory">Directory</param>
    /// <param name="oldKey">The old keyword to be replaced</param>
    /// <param name="newKey">The new keyword</param>
    private static void ReplaceKeywordRecursive(DirectoryInfo directory, string oldKey, string newKey)
    {
        var subFiles = directory.GetFiles();
        if (subFiles.Any())
            Task.Factory.StartNew(() => subFiles.AsParallel().ForAll(
                subFileItem => CheckAndRenameFile(subFileItem, oldKey, newKey)));

        var subDirectories = directory.GetDirectories();
        if (subDirectories.Any())/* && match the old key*/
            RenameDirectory(directory, newKey);
        else
            Task.Factory.StartNew(() => subDirectories.AsParallel().ForAll(subDirectoryItem =>
                ReplaceKeywordRecursive(subDirectoryItem, oldKey, newKey)));
    }

    /// <summary>
    /// 重命名
    /// </summary>
    /// <param name="directory">需要被重命名的文件夹</param>
    /// <param name="newName">新名字</param>
    /// <exception cref="NotImplementedException"></exception>
    private static void RenameDirectory(DirectoryInfo directory, string newName)
    {
        Directory.Move(directory.FullName,Path.Combine(Path.GetDirectoryName(directory.FullName)!,newName));
    }

    /// <summary>
    /// 检查文件是否应该重命名，如果需要，重命名文件名并替换内容
    /// </summary>
    /// <param name="file">需要被检查的文件</param>
    /// <param name="oldKey">旧密钥</param>
    /// <param name="newKey">新密钥</param>
    /// <exception cref="NotImplementedException"></exception>
    private static void CheckAndRenameFile(FileInfo file, string oldKey, string newKey)
    {
        // 太难了，写不了
        throw new NotImplementedException();
    }
}